package com.zxtyshangjia.zxtyjms.order.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zxtyshangjia.zxtyjms.R;
import com.zxtyshangjia.zxtyjms.base.BaseFragment;
import com.zxtyshangjia.zxtyjms.order.adapter.OrderListAdapter;
import com.zxtyshangjia.zxtyjms.order.bean.ClassBean;
import com.zxtyshangjia.zxtyjms.order.bean.ClassifyBean;
import com.zxtyshangjia.zxtyjms.order.bean.OrderBean;
import com.zxtyshangjia.zxtyjms.order.bean.OrderData;
import com.zxtyshangjia.zxtyjms.utils.Api;
import com.zxtyshangjia.zxtyjms.utils.SpUtils;
import com.zxtyshangjia.zxtyjms.utils.ToastUtil;
import com.zxtyshangjia.zxtyjms.utils.WheelViewPopwindow;
import com.zxtyshangjia.zxtyjms.utils.refresh.BGANormalRefreshViewHolder;
import com.zxtyshangjia.zxtyjms.utils.refresh.BGARefreshLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by lv
 * 订单页
 */

public class TwoFragment extends BaseFragment {
    private View twoView;

    /**
     * 全部 有点击事件  class_id 传空
     */
    private TextView mAllOrderTv;

    /**
     * 前面的时间   有点击事件
     */
    private TextView mFrontTimeTv;

    /**
     * 后面的时间 有点击事件
     */
    private TextView mBehindTimeTv;

    /**
     * 分类 有点击事件
     */
    private TextView mClassOlderTv;

    /**
     * 筛选 有点击事件
     */
    private TextView mFilterOrderTv;

    /**
     * 订单数
     */
    private TextView mNumOrderTV;

    /**
     * 订单收益
     */
    private TextView mIncomeOrderTv;

    /**
     * 订单列表
     */
//    private ListViewForScrollView mOrderList;

    private ListView mOrderList;

    /**
     * 下拉刷新 上拉加载布局
     */
    private BGARefreshLayout mOrderRefresh;


    /**
     * 判断是下拉刷新还是加载更多
     */
    private boolean refreshOrLoad = true;
    private int startIndex = 1;

    /**
     * 下拉刷新加载更多 头脚布局选择
     */
    private BGANormalRefreshViewHolder refreshViewHolder;

    /**
     * 适配器
     */
    private OrderListAdapter orderListAdapter;

    private Object object;

    /**
     * 日历
     */
    private DatePicker dpPicker;

    /**
     * 和后端交互的参数
     */
    private String e_id;
    private String start_time = "";
    private String end_time = "";
    private String class_id = "";

    private int index;

    /**
     * 订单列表数组
     */

    private OrderBean bean;

    private ArrayList<OrderData.OrderList> orderList = new ArrayList<>();

    /**
     * 分类数组
     */

    private ClassBean cBean;

    private ArrayList<ClassifyBean> classList = new ArrayList<>();

    private List<String> className = new ArrayList<>();

    /**
     * 是否选择了起 / 止时间
     */
    private Boolean isFront = false;
    private Boolean isBehind = false;

    /**
     * 是否选择了分类
     */
    private Boolean isClass = false;

    private int timeType;
    /*
     * 当前年
     */
    int year = 0;
    /**
     * 当前月
     */
    int mMonth = 0;

    int dayOfMonth = 0;

    private String time1;
    private String time2;
    private Boolean isRight = false;


    /**
     * 下拉刷新、上拉加载监听器
     */
    private BGARefreshLayout.BGARefreshLayoutDelegate refreshLayoutDelegate = new BGARefreshLayout.BGARefreshLayoutDelegate() {
        @Override
        public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
            startIndex = 1;
            refreshOrLoad = true;
            initOrderAbout(startIndex);   //初始化订单相关  包括订单数/收益/列表

        }

        @Override
        public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
            refreshOrLoad = false;
            initOrderAbout(++startIndex);
            return true;  //此处一定要返回true，否则不会出现正在加载的窗口;
        }
    };


    /**
     * 点击侦听
     */

    private View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (view.getId() == mAllOrderTv.getId()) {
                //全部

                isFront = false;
                isBehind = false;
                isClass = false;
                mFrontTimeTv.setText("月-日");
                mBehindTimeTv.setText("月-日");
                mClassOlderTv.setText("分类");
                class_id = "";
                start_time = "";
                end_time = "";

                mOrderRefresh.beginRefreshing();
                mFilterOrderTv.setTextColor((mActivity.getResources().getColor(R.color.gray_999999)));
                mFilterOrderTv.setBackgroundResource(R.drawable.shape_bg_tv);


                dpPicker.setVisibility(View.GONE);
                mOrderList.setVisibility(View.VISIBLE);


            } else if (view.getId() == mFrontTimeTv.getId()) {
                //开始时间

                dpPicker.setVisibility(View.VISIBLE);
                mOrderList.setVisibility(View.GONE);
                timeType = 1;

            } else if (view.getId() == mBehindTimeTv.getId()) {
                //结束时间

                dpPicker.setVisibility(View.VISIBLE);
                mOrderList.setVisibility(View.GONE);
                timeType = 2;


            } else if (view.getId() == mClassOlderTv.getId()) {
                //分类


                dpPicker.setVisibility(View.GONE);
                mOrderList.setVisibility(View.VISIBLE);

                new WheelViewPopwindow(getActivity(), className, mClassOlderTv, new WheelViewPopwindow.OnSuccessClick() {
                    @Override
                    public void onSuccessClick(int position, String content) {

                        Log.e("position & content ==", position + "  " + content);

                        isClass = true;
                        if (position == 0) {
                            class_id = "";
                        } else {
                            class_id = classList.get(position - 1).class_id;
                            Log.e("classList i name =====", classList.get(position - 1).name);
                        }

                        Log.e("class_id =====", class_id);

                        mFilterOrderTv.setTextColor((mActivity.getResources().getColor(R.color.mainColor)));
                        mFilterOrderTv.setBackgroundResource(R.drawable.shape_bg_tv_pass);


                    }
                }).showPop();

            } else if (view.getId() == mFilterOrderTv.getId()) {
                //点击进行筛选

                dpPicker.setVisibility(View.GONE);
                mOrderList.setVisibility(View.VISIBLE);
                if(Integer.parseInt(time1) > Integer.parseInt(time2)){
                    isRight = false;
                }else {
                    isRight = true;
                }

                if ((isFront && isBehind && isRight) || isClass) {

                    mOrderRefresh.beginRefreshing();

                } else {
                    if(!isRight){
                        ToastUtil.showToast("开始时间不能在结束时间之前哦");
                    }else {
                        ToastUtil.showToast("请您选择筛选条件");
                    }
                }
            }

        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (twoView == null) {
            twoView = View.inflate(mActivity, R.layout.fragment_two, null);
        }

        e_id = SpUtils.getInstance(mActivity).getString("e_id", "");

        bindViews();
        initData();
        bindListener();
        mOrderRefresh.beginRefreshing();
        return twoView;
    }

    private void bindViews() {
        //在此绑定view

        mAllOrderTv = (TextView) twoView.findViewById(R.id.all_order_tv);
        mFrontTimeTv = (TextView) twoView.findViewById(R.id.front_data_tv);
        mBehindTimeTv = (TextView) twoView.findViewById(R.id.behind_data_tv);
        mClassOlderTv = (TextView) twoView.findViewById(R.id.class_order_tv);
        mFilterOrderTv = (TextView) twoView.findViewById(R.id.filter_order_tv);


        mOrderList = (ListView) twoView.findViewById(R.id.order_list_lv);
        mOrderRefresh = (BGARefreshLayout) twoView.findViewById(R.id.order_refresh);
        dpPicker = (DatePicker) twoView.findViewById(R.id.dpPicker);

        View view = LayoutInflater.from(mActivity).inflate(R.layout.order_list_header, null);
        mNumOrderTV = (TextView) view.findViewById(R.id.num_order_tv);
        mIncomeOrderTv = (TextView) view.findViewById(R.id.income_order_tv);
        mOrderList.addHeaderView(view);

    }

    private void bindListener() {
        //在此绑定监听器
        mAllOrderTv.setOnClickListener(mClickListener);
        mFrontTimeTv.setOnClickListener(mClickListener);
        mBehindTimeTv.setOnClickListener(mClickListener);
        mClassOlderTv.setOnClickListener(mClickListener);
        mFilterOrderTv.setOnClickListener(mClickListener);

        //初始化监听事件
        mOrderRefresh.setDelegate(refreshLayoutDelegate);

    }

    private void initData() {
        //在此处理数据

        initClassList();  //初始化分类列表

        initDate();//初始化 日期时间

        initList();  //初始化订单列表

    }

    private void initList() {

        refreshViewHolder = new BGANormalRefreshViewHolder(getContext(), true, true);
        mOrderRefresh.setRefreshViewHolder(refreshViewHolder);
        orderListAdapter = new OrderListAdapter(mActivity, new ArrayList<OrderData.OrderList>());
        mOrderList.setAdapter(orderListAdapter);


    }

    /**
     * 初始化信息时间
     */
    private void initDate() {
        Calendar calendar = Calendar.getInstance();
        // 获得日历对象
        Calendar c = Calendar.getInstance();

        year = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH) + 1;


        dpPicker.init(year, mMonth, dayOfMonth, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                TwoFragment.this.year = year;
                TwoFragment.this.mMonth = monthOfYear + 1;
                TwoFragment.this.dayOfMonth = dayOfMonth;

                Log.e("dayOfMonth=========", dayOfMonth + "");
                dpPicker.setVisibility(View.GONE);
                mOrderList.setVisibility(View.VISIBLE);
                if (TwoFragment.this.mMonth < 10) {

                    if (TwoFragment.this.dayOfMonth < 10) {
                        if (timeType == 1) {
                            mFrontTimeTv.setText("0" + TwoFragment.this.mMonth + "-0" + TwoFragment.this.dayOfMonth);
                            isFront = true;
                            start_time = TwoFragment.this.year + "-" + mFrontTimeTv.getText().toString();
                            Log.e("start_time ===== ", start_time);
                            time1 = TwoFragment.this.year + "0" + TwoFragment.this.mMonth + "0" + TwoFragment.this.dayOfMonth;
                            Log.e("time1 ===== ", time1);
                        } else {
                            mBehindTimeTv.setText("0" + TwoFragment.this.mMonth + "-0" + TwoFragment.this.dayOfMonth);
                            isBehind = true;
                            end_time = TwoFragment.this.year + "-" + mBehindTimeTv.getText().toString();
                            Log.e("end_time ===== ", end_time);
                            time2 = TwoFragment.this.year + "0" + TwoFragment.this.mMonth + "0" + TwoFragment.this.dayOfMonth;
                            Log.e("time2 ===== ", time2);
                        }
                    } else {

                        if (timeType == 1) {
                            mFrontTimeTv.setText("0" + TwoFragment.this.mMonth + "-" + TwoFragment.this.dayOfMonth);
                            isFront = true;
                            start_time = TwoFragment.this.year + "-" + mFrontTimeTv.getText().toString();
                            Log.e("start_time ===== ", start_time);
                            time1 = TwoFragment.this.year + "0" + TwoFragment.this.mMonth +""+ TwoFragment.this.dayOfMonth;
                            Log.e("time1 ===== ", time1);
                        } else {
                            mBehindTimeTv.setText("0" + TwoFragment.this.mMonth + "-" + TwoFragment.this.dayOfMonth);
                            isBehind = true;
                            end_time = TwoFragment.this.year + "-" + mBehindTimeTv.getText().toString();
                            Log.e("end_time ===== ", end_time);
                            time2 = TwoFragment.this.year + "0" + TwoFragment.this.mMonth +""+  TwoFragment.this.dayOfMonth;
                            Log.e("time2 ===== ", time2);
                        }

                    }


                } else {

                    if (TwoFragment.this.dayOfMonth < 10) {
                        if (timeType == 1) {
                            mFrontTimeTv.setText(TwoFragment.this.mMonth + "-0" + TwoFragment.this.dayOfMonth);
                            isFront = true;
                            start_time = TwoFragment.this.year + "-" + mFrontTimeTv.getText().toString();
                            Log.e("start_time ===== ", start_time);
                            time1 = TwoFragment.this.year  +""+ TwoFragment.this.mMonth + "0"+ TwoFragment.this.dayOfMonth;
                            Log.e("time1 ===== ", time1);
                        } else {
                            mBehindTimeTv.setText(TwoFragment.this.mMonth + "-0" + TwoFragment.this.dayOfMonth);
                            isBehind = true;
                            end_time = TwoFragment.this.year + "-" + mBehindTimeTv.getText().toString();
                            Log.e("end_time ===== ", end_time);
                            time2 = TwoFragment.this.year +"" + TwoFragment.this.mMonth + "0"+ TwoFragment.this.dayOfMonth;
                            Log.e("time2 ===== ", time2);
                        }
                    } else {

                        if (timeType == 1) {
                            mFrontTimeTv.setText(TwoFragment.this.mMonth + "-" + TwoFragment.this.dayOfMonth);
                            isFront = true;
                            start_time = TwoFragment.this.year + "-" + mFrontTimeTv.getText().toString();
                            Log.e("start_time ===== ", start_time);
                            time1 = TwoFragment.this.year +"" + TwoFragment.this.mMonth + ""+ TwoFragment.this.dayOfMonth;
                            Log.e("time1 ===== ", time1);
                        } else {
                            mBehindTimeTv.setText(TwoFragment.this.mMonth + "-" + TwoFragment.this.dayOfMonth);
                            isBehind = true;
                            end_time = TwoFragment.this.year + "-" + mBehindTimeTv.getText().toString();
                            Log.e("end_time ===== ", end_time);
                            time2 = TwoFragment.this.year +"" + TwoFragment.this.mMonth + ""+ TwoFragment.this.dayOfMonth;
                            Log.e("time2 ===== ", time2);
                        }
                    }
                }

                if (isFront && isBehind) {
                    mFilterOrderTv.setTextColor((mActivity.getResources().getColor(R.color.mainColor)));
                    mFilterOrderTv.setBackgroundResource(R.drawable.shape_bg_tv_pass);
                }

            }
        });


    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mOrderRefresh.endRefreshing();
                    break;
                case 1:
                    mOrderRefresh.endLoadingMore();
                    break;
            }
        }
    };


    /**
     * 初始化订单相关  包括订单数/收益/列表
     */
    private void initOrderAbout(int startIndex) {

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
                .url(Api.ORDER_LIST_URL + "?p=" + startIndex + "&e_id=" + e_id + "&start_time=" + start_time
                        + "&end_time=" + end_time + "&class_id=" + class_id)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {
                    Log.e("response =========", String.valueOf(response));
                    Class responseClass = OrderBean.class;
                    final String res = response.body().string();
                    Log.e("res =========", res);
                    object = new Gson().fromJson(res, responseClass);

                } catch (Exception e) {
                    Log.e("Exception e=======", "error");
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mOrderRefresh.endRefreshing();
                            object = null;
                            orderList.clear();
//                            mIncomeOrderTv.setText("0.00");
//                            mNumOrderTV.setText("0");
                        }
                    });
                }

                if (object != null && object instanceof OrderBean) {
                    bean = (OrderBean) object;
                    if (bean.flag.equals("success")) {
                        //获取成功

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIncomeOrderTv.setText(bean.data.total);
                                mNumOrderTV.setText(bean.data.order_num);
                            }
                        });


                        if (refreshOrLoad) {
                            //下拉刷新
                            if (bean.data.list == null) {
                                orderList.clear();
                            }else if(bean.data.list.size() == 0){
                                orderList.clear();
                            } else if (bean.data.list.size() > 0) {
                                orderList.clear();
                                orderList.addAll(bean.data.list);
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    orderListAdapter.refreshData(orderList, refreshOrLoad);
                                    Message msg = new Message();
                                    msg.what = 0;
                                    mHandler.sendMessage(msg);
                                }
                            });

                        } else {
                            //上拉加载更多
                            if (bean.data == null) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        refreshViewHolder.hideLoadingMoreImg();
                                        refreshViewHolder.updateLoadingMoreText("没有更多了");
                                        Message msg = new Message();
                                        msg.what = 1;
                                        mHandler.sendMessageDelayed(msg, 2000);
                                    }
                                });
                            } else {
                                if (bean.data.list == null) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            refreshViewHolder.hideLoadingMoreImg();
                                            refreshViewHolder.updateLoadingMoreText("没有更多了");
                                            Message msg = new Message();
                                            msg.what = 1;
                                            mHandler.sendMessageDelayed(msg, 2000);
                                        }
                                    });
                                } else {
                                    orderList.addAll(bean.data.list);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            orderListAdapter.refreshData(orderList, refreshOrLoad);
                                            refreshViewHolder.showLoadingMoreImg();
                                            refreshViewHolder.updateLoadingMoreText("正在加载...");
                                            Message msg = new Message();
                                            msg.what = 1;
                                            mHandler.sendMessageDelayed(msg, 2000);
                                        }
                                    });
                                }

                            }
                        }
                    } else {
                        ToastUtil.showToast(bean.message);
                        if (refreshOrLoad) {
                            Message msg = new Message();
                            msg.what = 0;
                            mHandler.sendMessage(msg);
                        } else {
                            Message msg = new Message();
                            msg.what = 1;
                            mHandler.sendMessageDelayed(msg, 2000);
                        }
                    }
                }

            }
        });

    }


    /**
     * 初始化分类列表
     */
    private void initClassList() {


        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
                .url(Api.CASH_AGENT + "?e_id=" + e_id)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //解析返回的结果
                try {
                    Log.e("=========response", String.valueOf(response));
                    Class responseClass = ClassBean.class;
                    final String res = response.body().string();
                    Log.e("=========res", res);
                    object = new Gson().fromJson(res, responseClass);
                } catch (Exception e) {
                    Log.e("=======", "error");
                    return;
                }
                if (object != null && object instanceof ClassBean) {
                    cBean = (ClassBean) object;
                    if (cBean.flag.equals("success")) {

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                classList.addAll(cBean.data.classify);

                                if (classList.size() > 0) {
                                    mClassOlderTv.setVisibility(View.VISIBLE);

                                    className.add("全部");
                                    for (int i = 0; i < classList.size(); i++) {
                                        className.add(classList.get(i).name);
                                    }
                                } else {
                                    mClassOlderTv.setVisibility(View.GONE);
                                }

                                Log.e("classList =======", classList.toString());


                            }
                        });

                    }
                }
            }
        });
    }

    @Override
    protected void lazyLoad() {

    }

    @Override
    public void onClick(View view) {

    }
}
